//(0, 0)->(n-1, n-1) 可走最短路径中的最大值 dijkstra
class Solution {
public:
    const int INF=0x3f3f3f3f;
    const int nxt[4][2]={{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    int n;
    bool checkpos(int x, int y) {return 0<=x&&x<n&&0<=y&&y<n;}
    void dijkstra(vector<vector<int>> &grid, vector<vector<int>> &vis, int x, int y, int mx)
    {
        if(vis[x][y]<mx) return; //不能更新这条路径的答案
        vis[x][y]=mx;
        for(auto &[dx, dy]:nxt)
        {
            int nx=x+dx, ny=y+dy;
            if(checkpos(nx, ny)&&max(mx, grid[nx][ny])<vis[nx][ny]) //在范围内&&可以更新
                dijkstra(grid, vis, nx, ny, max(mx, grid[nx][ny]));
        }
    }

    int swimInWater(vector<vector<int>>& grid) {
        n=grid.size();
        vector<vector<int>> vis(n, vector<int>(n, INF));
        dijkstra(grid, vis, 0, 0, grid[0][0]);
        return vis[n-1][n-1];
    }
};